var app = getApp()
Page({
	data : {
		list : [] , 
		height : '100%' , 
		msg : '' , 
		scrollTop : 0 , 
		looks : app.globalData.looks , //表情包
		activeLook : 'w' , // 选择的表情包分组
		openLook : false , //打开选择表情包
		useLook : false , //选择好后表情包
		cursor : 0 , // 输入光标位置
		count : 0 , // 总人数
	} , 
	onLoad : function(){
		app.openConnect(app.globalData.host , app.globalData.port , this.requestMessage , this);
		wx.getSystemInfo({
			success : (res) => {
				var saveItem = {
					height : res.screenHeight - 120 , 
					nickname : app.globalData.userName , 
				};
				saveItem.scrollTop = saveItem.height;
				this.setData(saveItem);
				// this.setData({height : res.screenHeight});
			}
		})
		app.globalData.chatList = [];
		let list = wx.getStorageSync('list');
		if (list) {
			app.globalData.chatList = JSON.parse(list);
		}
		if(app.globalData.onMessage.length > 0){
			app.globalData.onMessage.forEach((item) => {
				this.requestMessage(item);
			});
		}else{
			this.setData({
				list : app.globalData.chatList , 
				scrollTop : this.data.scrollTop + 120 , 
			})
		}
	} , 
	onUnload : function(){
		// 点击返回后，恢复列表数据
		wx.setStorageSync('list' , JSON.stringify(app.globalData.chatList));
		// app.sendMsg(null , 'logout');
	} , 
	// 收到消息
	requestMessage : function(res){
		let count = 0;
		if(res.type != 'system'){
			// 显示消息，替换带有特殊的表情
			res.data = app.showMsg(res.data);
		}else{
			count = res.count;
			wx.setNavigationBarTitle({
				title : '共有' + count + '个人在群聊' , 
				success : function(){
					console.log('success');
				}
			});
		}
		app.globalData.chatList.push(res);
		this.setData({
			list : app.globalData.chatList , 
			scrollTop : this.data.scrollTop + 120 , 
			count : count , 
		})
	} , 
	// 更改Input
	changeInput : function(e){
		var value = e.detail.value;
		this.setData({
			msg : value
		})
	} , 
	// 表情分组
	useLookGroup : function(e){
		var group = e.currentTarget.dataset.group;
		this.setData({
			activeLook : group , 
		})
	} , 
	// 打开表情选择
	openLook : function(){
		var openLook = this.data.openLook;
		openLook = openLook ? false : true;
		this.setData({
			openLook : openLook
		})
	} , 
	// 选中表情
	useLook : function(e){
		let map = e.currentTarget.dataset;
		let value = map.key , msg = this.data.msg , group = map.group , cursor = this.cursor;
		let lookItem = '[' + group + ':' + value + ']';
		if(msg){
			if (cursor > 0) {
				let matchs = msg.substr(0 , cursor) , alldata = msg.substr(cursor , msg.length)
				matchs += lookItem
				msg = matchs + alldata;
			}else{
				msg += lookItem
			}
		}else{
			msg = lookItem
		}
		this.setData({msg : msg});
	} , 
	// 获取焦点时把选择框全部隐藏
	closeUse : function(e){
		// this.setData({
		// 	openLook : false , 
		// })
	} , 
	// 失去焦点时获取输入框的光标位置
	inputBlur: function(e){
		this.cursor = e.detail.cursor;
	} , 
	// 发送消息
	sendMsg : function(){
		if(!this.data.msg){
			return;
		}
		app.sendMsg(this.data.msg , 'normal');
		this.setData({
			msg : '' , 
		})
	}
})